<%--
  Created by IntelliJ IDEA.
  User: lzy
  Date: 18-8-2
  Time: 上午8:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index</title>
</head>
<body>
<%
    /*
     * 若可以获取到请求参数loginName，则打印出欢迎信息，把登录信息存储到Cookie中，
     * 并设置Cookie的最大时效为30s
     * 从Cookie中读取用户信息，若存在则打印欢迎信息
     * 若既没有请求参数，也没有Cookie，则重定向到login.jsp
     */
    String user = request.getParameter("userName");
    if (user != null && !"".equals(user.trim())) {
        out.print("Welcome " + user + " for your first login");
        Cookie cookie = new Cookie("userName", user);
        cookie.setMaxAge(10);
        response.addCookie(cookie);
        return;
    } else {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("userName".equals(cookie.getName())) {
                    user = cookie.getValue();
                }
            }
        }
    }
    if (user != null && !"".equals(user.trim())) {
        out.print("hello " + user);
    } else {
        // 若既没有请求参数，也没有cookie，则定向到login.jsp
        response.sendRedirect("login.jsp");
    }

%>
</body>
</html>
